﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Data;

namespace qdata
{
   public class KyzData
   {
       private static volatile KyzData m_instance = null;

       public static KyzData GetInstance()
       {
           if (m_instance == null)
           {
               lock (typeof(KyzData))
               {
                   if (m_instance == null)
                   {

                       m_instance = new KyzData();
                   }
               }
           }
           return m_instance;
       }


       public string GetHmtl(string url)
       {
           return Common.GetInstance().GetHtmlCode(url);
           
       }

       public void Save(string[] SarCityArr, string[] EndCityArr,   string site)
       {
           string url = "http://www.keyunzhan.com/zhandaozhan_search.php?find_type=2&shousuo=2&startstate={0}&endstate={1}";
           
           foreach (string s1 in SarCityArr)
           {
               foreach (string s2 in EndCityArr)
               {
                   SaveCarstation(string.Format(url, s1, s2), s1, s2, site);
                   //DoTotal(s1, s2, site);
               }
           }
       }

       public void SaveData(Hashtable hs,string site)
       {
           string sql = "insert into Carbanci(StationName,ECity,Scity,Lichen,Fdate,piaojia,EndSite) ";
           string sqlval = string.Format ("values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
                                        hs["station"].ToString(), hs["ecity"].ToString(), hs["Scity"].ToString(), hs["lichen"].ToString(), hs["checi"].ToString(), hs["chefei"].ToString(), site);

           string sql2 = "select * from CarStation where Name='" + hs["station"].ToString() + "'";

           Common.GetInstance().ExecuteDataTable(sql + sqlval );
           DataTable dt = Common.GetInstance().ExecuteDataTable(sql2);
          if (dt == null || dt.Rows.Count <= 0)
          {
              sql2 = string.Format("insert into CarStation (Name,Descrtion,Address,Phone,EndSite,EndSite,ECity,Scity) values('{0}','{1}','{2}','{3}','{4}','{5}')", hs["station"].ToString(), "", hs["ad"].ToString(), hs["ph"].ToString(), site,hs["ecity"].ToString(), hs["Scity"].ToString());
              Common.GetInstance().ExecuteDataTable(sql2);
          }
          //sql+sqlval
       }

       public void SaveCarstation(string url,string scity,string ecity,string site)
       {
         
           List<Hashtable> ls = new List<Hashtable>();
           string html = GetHmtl(url);
           List<string> sum = new List<string>();
           var s1 = Regex.Matches(html, @"(?is)(<div class=""car_left_detail01_rows"">)(.*?)(纠错</a>)");
           if (s1 == null || s1.Count <= 0)
           {
               GetErrStationInfo(html,scity,ecity, site);
           }
           else
           {
               foreach (Match m1 in s1)
               {
                   Hashtable hs = new Hashtable();
                   string pattern = @"(?is)(<div class=""car_left_detail01_rows_col01"">)(.*?)(</div>)";
                   var s2 = Regex.Matches(m1.Groups[0].Value, pattern);

                   hs.Add("Scity", scity);
                   hs.Add("ecity", ecity);
                   hs.Add("station", GetATitle(s2[1].Groups[2].Value));
                   string url1 = Common.GetInstance().GetUrl(s2[1].Groups[2].Value);
                   GetStationDetail(url1, hs);
                   pattern = @"(?is)(<div class=""car_left_detail01_rows_col02"">)(.*?)(</div>)";
                   var s3 = Regex.Matches(m1.Groups[0].Value, pattern);
                   hs.Add("checi", s3[0].Groups[2].Value);

                   pattern = @"(?is)(<div class=""car_left_detail01_rows_col02"" style[^>]*>)(.*?)(</div>)";
                   var s4 = Regex.Matches(m1.Groups[0].Value, pattern);
                   hs.Add("lichen", s4[0].Groups[2].Value);

                   pattern = @"(?is)(<div class=""car_left_detail01_rows_col03"">)(.*?)(</div>)";
                   var s5 = Regex.Matches(m1.Groups[0].Value, pattern);
                   hs.Add("chefei", s5[0].Groups[2].Value);
                   SaveData(hs, site);


               }
           }

       }
       public void DoTotal(string[] scityArr, string[] ecityArr, string site)
       {
            foreach (string s1 in scityArr)
           {
               foreach (string s2 in ecityArr)
               {
                    
                   DoTotal(s1, s2, site);
               }
           }
       }

       public void DoTotal(string scity, string ecity, string site)
       {
           GetCarStation gc = new GetCarStation();
           DataTable dt = gc.ExecuteDataTable(string.Format("select * from Carbanci where  Scity like '%{0}%' and  ECity like '%{1}%'", scity, ecity));
           if (dt == null || dt.Rows.Count <= 0) return;
           string AllTotal = dt.Rows.Count.ToString();
           string distanct = dt.Rows[0]["Lichen"].ToString();
           DataTable dt3 = gc.ExecuteDataTable(string.Format("select top 1 * from Carbanci where Scity like '%{0}%' and  ECity like '%{1}%'", scity, ecity) + " order by piaojia asc  ");
           DataTable dt4 = gc.ExecuteDataTable(string.Format("select top 1 * from Carbanci where Scity like '%{0}%' and  ECity like '%{1}%'", scity, ecity) + " order by piaojia desc   ");

           string Cheapest = dt3.Rows[0]["piaojia"].ToString();
           string chpcheci = dt3.Rows[0]["fdate"].ToString();
           string expensive = dt4.Rows[0]["piaojia"].ToString();
           string expensivecheci = dt4.Rows[0]["fdate"].ToString();

           DataTable dttemp = gc.ExecuteDataTable(string.Format("select * from [TotalBus] where Scity ='{0}' and  Ecity = '{1}'", scity, ecity));
           if (dttemp != null && dttemp.Rows.Count > 0)
           {
               string ustr = "update [TotalBus] set Distance='{0}',  Total='{1}', Cheapest='{2}',chpcheci='{3}',expensive='{4}',expensivecheci='{5}',EndSite='{6}'  where Scity ='{7}' and  Ecity = '{8}'";
               ustr = string.Format(ustr, distanct, AllTotal, Cheapest, chpcheci, expensive, expensivecheci, site, scity, ecity);
               gc.ExecuteDataTable(ustr);
           }
           else
           {
               string ustr = "insert into [TotalInfo] (Distance ,Total,Scity,Ecity ,Cheapest,chpcheci,expensive,expensivecheci,EndSite)  values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}' )";
               ustr = string.Format(ustr, distanct,  AllTotal, scity, ecity, Cheapest, chpcheci, expensive, expensivecheci, site);
               gc.ExecuteDataTable(ustr);
           }
       }



       public void  GetErrStationInfo(string html,string scity,string ecity ,string site)
       {
           string[] arr1 = null;
           string[] arr2 = null;
           var s1 = Regex.Matches(html,  @"(?is)(<span  style=""color:#0051AA; font-size:16px"" >)(.*?)(</span>)");
           if (s1.Count>0)
           {
               string tp = s1[0].Groups[2].Value.Replace("<br>","@");
               string[] arr = tp.Split('@');
              if (arr.Length > 0)
              {
                  arr1 = arr[0].Split(':');
                  arr2 = arr[1].Split(':');
              }
              else
              {
                  return;
              }

              string sql2 = "select * from CarStation where Name='" +  arr1[0] + "'";

              Common.GetInstance().ExecuteDataTable(sql2);
               DataTable dt = Common.GetInstance().ExecuteDataTable(sql2);
              if (dt == null || dt.Rows.Count <= 0)
              {
                  sql2 = string.Format("insert into CarStation (Name,Descrtion,Address,Phone,EndSite,ECity,Scity) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", arr1[0], "", arr2[1], arr1[1], site, ecity,scity );

                  Common.GetInstance().ExecuteDataTable(sql2);
              }
           }
          
           
       }

       public string GetATitle(string html)
       {
           var s1 = Regex.Matches(html, @"(?is)(<a[^>]*>)(.*?)(</a>)");
           if (s1.Count > 0)
               return s1[0].Groups[2].Value ;
           return string.Empty;
       }

       public void GetStationDetail(string url, Hashtable hs)
       {
           string html = GetHmtl("http://www.keyunzhan.com" + url);
           string pattern = @"(?is)(址：</span>)(.*?)(</p>)";
           var s1 = Regex.Matches(html, pattern);
           if (s1.Count > 0)
           {
               hs.Add("ad", s1[0].Groups[2].Value);

           }
           else
           {
               hs.Add("ad", "");
           }
           pattern = @"(?is)(话：</span><span class=""span_red"">)(.*?)(</span></p>)";
           var s2 = Regex.Matches(html, pattern);

           if (s2.Count > 0)
           {
               hs.Add("ph", s2[0].Groups[2].Value);

           }
           else
           {
               hs.Add("ph", "");
           }
       }


       public string GetBuschecil(string ECity, string Scity)
       {
           string str = "select a.*,b.Address,b.Phone from Carbanci as a left join CarStation as b on a.StationName=b.Name where a.ECity='{0}' and a.Scity='{1}'";
           str = string.Format(str, ECity, Scity);
           DataTable dt = Common.GetInstance().ExecuteDataTable(str);
           string temp = TotalData.GetInstance().ReaFile("buscheci.txt");
           string v="";
           foreach(DataRow dr in dt.Rows )
           {
               v +=TotalData.GetInstance().ChangeTempData(dr, temp)+"<br>";
           }
           return v;
       }

       public string GetBusStation(string ECity, string Scity)
       {
           string str = "select a.*  from CarStation as a where a.ECity='{0}' and a.Scity='{1}'";
           str = string.Format(str, ECity, Scity);
           DataTable dt = Common.GetInstance().ExecuteDataTable(str);
           string temp = TotalData.GetInstance().ReaFile("busStation.txt");
           string v="";
           foreach(DataRow dr in dt.Rows )
           {
               v +=TotalData.GetInstance().ChangeTempData(dr, temp)+"<br>";
           }
           return v;
       }
       

       public void WriteXmlInfo(string[] SArr, string[] EArr, string site)
       {
           string DongcheShowdata = "";
           string huocheShowdata = "";
           string content = string.Empty;
           GetCarStation gc = new GetCarStation();
           string jttemp = TotalData.GetInstance().ReaFile("bus.txt");
           foreach (string sCity in SArr)
           {
               foreach (string ECity in EArr)
               {
                   DataTable dtinfo = gc.ExecuteDataTable(string.Format("select  '{0}' as Scity , '{1}' as  Ecity,'{2}' as  site ", sCity, ECity, site));
                   if (dtinfo != null && dtinfo.Rows.Count > 0)
                   {
                       content += TotalData.GetInstance().ChangeTempData(dtinfo.Rows[0], jttemp);
                       string tempbusstation = GetBusStation(ECity, sCity);
                       string tempBuscheci = GetBuschecil(ECity, sCity);
                       content = content.Replace("|STATIONLIST|", tempbusstation);
                       string htmlsite = SiteData.GetInstance().GetOtherInfo(site);
                       content = content.Replace("|OTHERLIST|", htmlsite);

                       content = content.Replace("|CHECILIST|", tempBuscheci) + "\r\n \r\n\r\n";
                   }
               }
           }
           TotalData.GetInstance().Write("AskBuscheci.txt", content);

       }


    }
}
